import axios from 'axios'
import config from '@/config'
export function searchModel(model, data) {
    const url = config.serverURI + config.api.model_opt + model + '/' + 'search'
    return axios({
        method: 'post',
        url,
        data
    })
}



export function getModel(model, params, filters={}) {
    let search = ''
    for (let key in filters) {
        search += key + '/' + filters[key]
    }

    if (search) {
        search = '/' + search
    }
    return axios({
        method: 'get',
        url: config.serverURI + config.api.model_opt + model + search,
        params: params
    })
}

export function get(model, id) {
  return axios({
    method: 'get',
    url: config.serverURI + config.api.model_opt + model  + '/' + id,
    params: {}
  })
}

export function listModel(model) {
    return axios({
        method: 'options',
        url: config.serverURI + config.api.model_opt + model,
    })
}

export function addModel(model, params) {
    return axios({
        method: 'post',
        url: config.serverURI + config.api.model_opt + model,
        data: params
    })
}



export function updateModel(model, id, params) {
    return axios({
        method: 'post',
        url: config.serverURI + config.api.model_opt + model + '/' + id,
        data: params
    })
}

/**
 * 批量添加
 * @param model
 * @param datas
 * @returns {AxiosPromise}
 */
export function addModels(model, datas) {
  const _params = datas.map(item => {
    let _data = item;
    delete _data["id"];
    return {"params": _data};
  });
  const _items = {"items": _params};
  return axios({
    method: 'post',
    url: config.serverURI + config.api.model_opt + model+"/batch",
    data: _items
  })
}

/**
 * 批量更新
 * @param model
 * @param id
 * @param params
 * @returns {AxiosPromise}
 */
export function updateModels(model, params) {
  const _params = params.map(item => {
    let _data = item;
    const _id = _data.id;
    return {"id":_id,"params": _data};
  });
  const _items = {"items": _params};
  return axios({
    method: 'PUT',
    url: config.serverURI + config.api.model_opt + model + '/batch',
    data: _items
  })
}

export function deleteModel(model, id) {
    return axios({
        method: 'delete',
        url: config.serverURI + config.api.model_opt + '/' + model + '/' + id,
    })
}
